package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.conmmon.BaseContext;
import com.itheima.conmmon.CustomException;
import com.itheima.conmmon.R;
import com.itheima.domain.Dish;
import com.itheima.domain.Setmeal;
import com.itheima.domain.ShoppingCart;
import com.itheima.service.DishService;
import com.itheima.service.SetMealService;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liwanhu
 * @datetime 2021/10/30 19:54
 */
@RestController
@RequestMapping("shoppingCart")
@Slf4j
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private DishService dishService;

    @Autowired
    private SetMealService setMealService;

    /**
     * 实战第一天
     * 用户端,添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> save(@RequestBody ShoppingCart shoppingCart) {
        log.info("购物车数据:{}", shoppingCart);
        //设置用户id，指定当前是哪个用户的购物车数据
        Long userId = BaseContext.getCreatId();
        shoppingCart.setUserId(userId);
        //获取菜品
        Long dishId = shoppingCart.getDishId();
        //构造条件判断
        QueryWrapper<ShoppingCart> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        //判断添加的是否是菜品
        if (dishId != null) {
            qw.eq("dish_id", dishId);
            //否则存入的则是套餐
        } else {
            qw.eq("setmeal_id", shoppingCart.getSetmealId());
        }
        //查询当前菜品或套餐是否在购物车中
        ShoppingCart cartServiceOne = shoppingCartService.getOne(qw);
        //如果在购物车中的话
        if (cartServiceOne != null) {
            //获取商品的数量
            Integer number = cartServiceOne.getNumber();
            //在已有的商品基础上加一
            cartServiceOne.setNumber(number + 1);
            shoppingCartService.updateById(cartServiceOne);
        } else {
            //如果不存在的话,给它添加1
            shoppingCart.setNumber(1);
            //赋给添加的时间
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            cartServiceOne = shoppingCart;
        }
        return R.success(cartServiceOne);
    }

    /**
     * 实战第一天
     * 用户端,查看购物车
     * @return
     */
    @GetMapping("list")
    public R<List<ShoppingCart>> list() {
        //根据id查看用户对应的购物车信息
        QueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new QueryWrapper<>();
        shoppingCartQueryWrapper.eq("user_id", BaseContext.getCreatId());
        //根据加入购物车的时间进行排序
        shoppingCartQueryWrapper.orderByDesc("create_time");
        //获取购物车表中的对象
        List<ShoppingCart> list = shoppingCartService.list(shoppingCartQueryWrapper);
        List<ShoppingCart> collect = list.stream().map((item) -> {
            ShoppingCart shoppingCart1 = new ShoppingCart();
            //将菜品信息拷贝到购物车中
            BeanUtils.copyProperties(item, shoppingCart1);
            //并给菜品信息提供对应的用户信息
            shoppingCart1.setUserId(BaseContext.getCreatId());
            /**
             * 优化
             */
            //获取菜品id
            Long dishId = item.getDishId();
            BigDecimal price;
            if (dishId != null) {
                Dish dish = dishService.getById(dishId);
                if (dish.getStatus() ==0){
                    throw new CustomException(dish.getName()+"菜品已下架,请看看其他的菜品吧");
                }
                price = dish.getPrice();
            } else {
                Long setmealId = item.getSetmealId();
                Setmeal setmeal = setMealService.getById(setmealId);
                if (setmeal.getStatus() ==0){
                    throw new CustomException("套餐已下架,请看看其他的菜品吧");
                }
                price = setmeal.getPrice();
            }
            shoppingCart1.setAmount(new BigDecimal(price.intValue()/100));
            //获取菜品id对应的菜品对象

            return shoppingCart1;
        }).collect(Collectors.toList());
        return R.success(list);
    }

    /**
     * 实战第一天
     * 用户端,清空购物车
     * @return
     */
    @DeleteMapping("clean")
    public R<String> clean() {
        QueryWrapper<ShoppingCart> qw = new QueryWrapper<>();
        //根据用户id清空购物车
        qw.eq("user_id", BaseContext.getCreatId());
        shoppingCartService.remove(qw);
        return R.success("删除成功");
    }

    /**
     * 实战第一天
     * 手机端,修改购物车中的数量
     * @param shoppingCart
     * @return
     */
    @PostMapping("sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart) {
        Long userId = BaseContext.getCreatId();
        shoppingCart.setUserId(userId);

        Long dishId = shoppingCart.getDishId();
        //获取菜品
        //构造条件判断
        QueryWrapper<ShoppingCart> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        //判断添加的是否是菜品
        if (dishId != null) {
            qw.eq("dish_id", dishId);
            //否则存入的则是套餐
        } else {
            qw.eq("setmeal_id", shoppingCart.getSetmealId());
        }
        //获取当前在购物车的商品
        ShoppingCart cartServiceOne = shoppingCartService.getOne(qw);
        //获取商品的数量
        Integer number = cartServiceOne.getNumber();
        //对商品数量减一
        cartServiceOne.setNumber(number -1);
        //清空数据
        if (number == 1){
            shoppingCartService.removeById(cartServiceOne);
            return R.success(cartServiceOne);
        }else {

            shoppingCartService.updateById(cartServiceOne);
            return R.success(cartServiceOne);
        }
    }
}
